package com.xuebusi.controller;

import com.xuebusi.common.ResultModel;
import com.xuebusi.common.util.CommonUtil;
import com.xuebusi.common.util.DateUtil;
import com.xuebusi.entity.Img;
import com.xuebusi.entity.User;
import com.xuebusi.service.ImgService;
import com.xuebusi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.util.List;
import java.util.Map;

/**
 * Created by SYJ on 2017/11/11.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ImgService imgService;

    /**
     * 用户列表
     * @param map
     * @return
     */
    @GetMapping(value = {"", "/list"})
    public ModelAndView findAll(Map<String, Object> map) {
        List<User> userList = userService.findAll();
        map.put("userList", userList);
        return new ModelAndView("/user/list");
    }

    /**
     * 用户表单页
     * @param id
     * @return
     */
    @GetMapping(value = "/toUpdate")
    public ModelAndView toUpdate(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id, Map<String, Object> map) {
        if (id > 0) {
            User user = userService.getUserById(id);
            map.put("user", user);
        }
        return new ModelAndView("/user/form", map);
    }

    /**
     * 修改用户
     * @param request
     * @return
     */
    @PostMapping(value = "/save")
    public ModelAndView save(MultipartHttpServletRequest request) {
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String birthday = request.getParameter("birthday");

        ResultModel<List<Img>> resultModel = imgService.upload(request, "headimg");
        List<Img> imgList = resultModel.getData();
        String imgPath = null;
        if (!CollectionUtils.isEmpty(imgList)) {
            imgPath = imgList.get(0).getImgPath();
        }
        User user = new User();
        if (CommonUtil.toString(id)) {
            user.setId(Integer.parseInt(id));
        }
        user.setUsername(username);
        if(!StringUtils.isEmpty(birthday)) {
            int age = DateUtil.getAgeFromBirthTime(birthday);
            user.setAge(age);
        }
        user.setAddress(address);

        user.setBirthday(DateUtil.toDate(birthday));
        user.setPhone(phone);
        if (CommonUtil.toString(gender)) {
            user.setGender(Integer.parseInt(gender));
        }
        if (!StringUtils.isEmpty(imgPath)) {
            user.setHeadimg(imgPath);
        }

        if (user.getId() != null && user.getId() > 0) {
            User userFromDb = userService.getUserById(user.getId());
            if (userFromDb != null) {
                userFromDb.setGender(user.getGender());
                userFromDb.setPhone(user.getPhone());
                userFromDb.setBirthday(user.getBirthday());
                userFromDb.setAddress(user.getAddress());
                userFromDb.setAge(user.getAge());
                userFromDb.setUsername(user.getUsername());
                if (!StringUtils.isEmpty(user.getHeadimg())) {
                    userFromDb.setHeadimg(user.getHeadimg());
                }
                userService.update(userFromDb);
            }
        } else {
            userService.insert(user);
        }
        return new ModelAndView(new RedirectView("/user/list"));
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping(value = "/del/{id}")
    @ResponseBody
    public ResultModel del(@PathVariable("id") Integer id) {
        //软删除
        if (id > 0) {
            User user = userService.getUserById(id);
            user.setDelflag(1);//1删除, 0未删除
            int count = userService.update(user);
            if (count > 0) {
                return new ResultModel().success(count);
            }
        }
        return new ResultModel().fail();
    }
}
